package com.atguigu.ssyx.search.receiver;

import com.atguigu.ssyx.mq.constant.MqConst;
import com.atguigu.ssyx.search.service.SkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * ClassName: SkuReceiver
 * Package: com.atguigu.ssyx.search.receiver
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-09-27
 * Time: 16:35
 */

@Component
public class SkuReceiver {
    //接收消息 相当于就是监听器 监听有没有消息发送过来

    //SkuService这里面有上架 下架接口的方法
    @Autowired
    private SkuService skuService;

    //监听 绑定哪个交换机 哪个路由key  value队列的信息
    //durable表示消息持久化 exchange 交换机 key就是路由key
    //交换机和路由key要和发送端保持一直
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_UPPER,durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_GOODS_DIRECT),
            key = {MqConst.ROUTING_GOODS_UPPER}
    ))
    public void upperSku(Long skuId, Message message, Channel channel) throws IOException {
        //参数 发送来的消息  消息  信道
        if (skuId != null){
            //上架
            skuService.upperSku(skuId);
        }
        //手动确定 参数表示 消息标识  是否有多个参数
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


    //下架
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER,durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_GOODS_DIRECT),
            key = {MqConst.ROUTING_GOODS_LOWER}
    ))
    public void lowerSku(Long skuId, Message message, Channel channel) throws IOException {
        if (skuId != null) {
            skuService.lowerSku(skuId);
        }
        //消费端的手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
